/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import java.io.PrintStream;
import tal.drivechain.chain.Chain;
import tal.drivechain.parsing.Tokenizer;

/**
 *
 * @author eisental
 */
public abstract class Spy {
    protected PrintStream out;
    protected Chain chain;
    private String spyType = "unknown", spyCriteria;

    public void init(String type, String criteria, Chain chain, PrintStream out) {
        this.chain = chain;
        this.out = out;
        this.spyCriteria = criteria;
        this.spyType = type;
        setupSpy(criteria);
    }

    public abstract void setupSpy(String criteria);

    public static Spy createSpy(String spyCommand, Chain chain, PrintStream out) throws IllegalArgumentException {
        String[] typeCriteria = new Tokenizer(spyCommand, ':').getTokens();
        if (typeCriteria.length!=2)
            throw new IllegalArgumentException("Invalid spy command syntax (should be: <spy type>:<spy criteria> )");

        if (typeCriteria[0].equals("var") || typeCriteria[0].equals("variable")) {
            Spy varSpy = new VariableSpy();
            varSpy.init(typeCriteria[0], typeCriteria[1], chain, out);
            return varSpy;
        } else if (typeCriteria[0].equals("node")) {
            Spy nodeSpy = new NodeSpy();
            nodeSpy.init(typeCriteria[0], typeCriteria[1], chain, out);
            return nodeSpy;
        } else throw new IllegalArgumentException("Unknown spy type: " + typeCriteria[0]);
    }

    public abstract void destroy();

    public Chain getChain() {
        return chain;
    }

    @Override
    public String toString() {
        return spyType + ": " + spyCriteria;
    }

    public abstract String report();

    public abstract String getName();
}
